package tcp

import "log"

type MessageHandler interface {
	OnMessage(ctx *SessionContext, buf *Buffer)
	Write(ctx *SessionContext, buf *Buffer)
	OnConnected(ctx *SessionContext)
	OnDisconnected(ctx *SessionContext)
}

type node struct {
	MessageHandler
	Pre  *node
	Next *node
}

func (n *node) addNext(handler MessageHandler) *node {
	newN := &node{
		MessageHandler: handler,
		Pre:            n,
	}

	n.Next = newN
	return newN
}

type BaseHandler struct{}

func (b BaseHandler) OnConnected(ctx *SessionContext) {
	if ctx.goNext() {
		ctx.node.OnConnected(ctx)
	}
}
func (b BaseHandler) OnDisconnected(ctx *SessionContext) {
	if ctx.goNext() {
		ctx.node.OnDisconnected(ctx)
	}
}
func (b BaseHandler) OnMessage(ctx *SessionContext, buf *Buffer) {
	ctx.NextOnMessage(buf)
}
func (b BaseHandler) Write(ctx *SessionContext, buf *Buffer) {
	ctx.PreWrite(buf)
}

type HeadHandler struct{ BaseHandler }

func (h HeadHandler) Write(ctx *SessionContext, buf *Buffer) {
	if _, err := ctx.TCPConn.Write(buf.Frame()); err != nil {
		log.Println(err.Error())
		return
	}
}
